<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="码值类型:">
        <el-input v-model="queryForm.codeType" placeholder="" clearable />
      </el-form-item>
      <el-form-item label="码值名:">
        <el-input v-model="queryForm.name" placeholder="" clearable />
      </el-form-item>
      <el-form-item label="时间范围:">
        <el-date-picker
          v-model="queryForm.time"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="searchData()"
       >查询</el-button
      >
      <el-button
        type="default"
        @click="
          () => {
            this.queryForm = {};
          }
        "
        >清空</el-button
      >
    </el-form>

    <el-button
      type="success"
      size="small"
      style="margin-bottom: 10px"
      icon="el-icon-document-add"
      @click="create()"
      v-if="hasPerm('code.add')">新增</el-button
    >

    <!-- 表格 -->
    <!-- v-loading="listLoading" -->
    <el-table
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      stripe
      highlight-current-row
      :key="tableKey"
    >
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        prop="codeType"
        label="码值类型"
        width="200"
        align="center"
      />
      <el-table-column prop="encoding" label="编码" width="80" align="center" />
      <el-table-column prop="name" label="码值名" width="120" align="center" />
      <el-table-column
        prop="sort"
        label="排序号"
        width="100"
        align="center"
        sortable
      />
      <el-table-column prop="detail" label="详情" align="center" />

      <el-table-column label="操作" width="200" align="center" v-if="hasPerm('code.update')|hasPerm('code.remove')">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="update(scope.row)"
            v-if="hasPerm('code.update')">修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeById(scope.row.id)"
            v-if="hasPerm('code.remove')">删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 拟态框 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogFormValue"
      :close="
        () => {
          this.$nextTick.CLForm.clearValidate();
        }
      "
    >
      <el-form
        ref="CLForm"
        :model="CLForm"
        :rules="menuValidateRules"
        label-width="120px"
      >
        <el-form-item label="码值类型" prop="codeType">
          <el-input v-model="CLForm.codeType" />
        </el-form-item>
        <el-form-item label="编码" prop="encoding">
          <el-input v-model="CLForm.encoding" />
        </el-form-item>
        <el-form-item label="码值名" prop="name">
          <el-input v-model="CLForm.name" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input v-model="CLForm.sort" />
        </el-form-item>
        <el-form-item label="详情" prop="detail">
          <el-input v-model="CLForm.detail" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restData()">取 消</el-button>
        <el-button type="primary" @click="append()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center"
      layout="total, prev, pager, next, jumper"
      @current-change="initTableList"
    />
  </div>
</template>
<script>
import codeLibraryList from "@/api/account/codeLibraryList";
import {getToken} from '@/utils/auth'
import {getInfo} from '@/api/login'

const codeLibraryForm = {
  codeType: "",
  encoding: "",
  name: "",
  sort: "",
  detail: "",
  userId: ""
};

export default {
  // data:{
  // },
  data() {
    //定义变量和初始值
    return {
      list: null, //查询之后接口返回集合
      page: 1, //当前页
      limit: 10, //每页记录数
      total: 0, //总记录数
      queryForm: {}, //查询条件form中的数据
      dialogFormVisible: false,
      CLForm: { ...codeLibraryForm },
      userId: 0,
      tableKey: 0,
      menuValidateRules: {
        //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
        codeType: [
          { required: true, trigger: "blur", message: "码值类型必须输入" },
          {
            validator: (rule, value, callback) => {
              if (/^[0-9a-zA-Z]{4,30}$/.test(value) == false) {
                callback(new Error("码值类型由4-20位数字或字母组成"));
              } else {
                callback();
              }
            },
          },
        ],
        encoding: [
          { required: true, trigger: "blur", message: "编码必须输入" },
          {
            validator: (rule, value, callback) => {
              if (/^[0-9]{1,4}$/.test(value) == false) {
                callback(new Error("编码由1-4位数字组成"));
              } else {
                callback();
              }
            },
          },
        ],
        name: [{ required: true, trigger: "blur", message: "码值名必须输入"},
        {
            validator: (rule, value, callback) => {
              if (/^.{1,30}$/.test(value) == false) {
                callback(new Error("码值名长度在 1 到 30 个字符"));
              } else {
                callback();
              }
            },
          }],
        sort: [{ required: true, trigger: "blur", message: "排序必须输入" },
        {
            validator: (rule, value, callback) => {
              if (/^[0-9]{1,4}$/.test(value) == false) {
                callback(new Error("排序码由1-4位数字组成"));
              } else {
                callback();
              }
            },
          }],
      },
      dialogFormValue: "新增",
    };
  },
  created() {
    //在页面渲染之前执行，一般调用methods定义的方法
    this.initTableList();
    getInfo(getToken()).then(res => {
      this.userId = res.data.userId
    })
  },
  methods: {
    //码值列表的方法
    initTableList(page = 1) {
      console.log('被调用')
      this.page = page;
      codeLibraryList
        .getCodeLibraryListPage(this.page, this.limit, this.queryForm)
        .then((response) => {
          //response接口返回的数据
          this.list = response.data.rows;
          this.total = response.data.total;
          this.tableKey = Math.random()
          console.log(response.data.rows)
        }) //请求成功
        .catch((error) => {
          console.log(error);
        }); //请求失败
    },
    create() {
      this.dialogFormVisible = true;
      this.CLForm = { ...codeLibraryForm };
      //等弹窗里的form表单的dom渲染完在执行this.$refs.CLForm.clearValidate()，去除验证
      this.$nextTick(() => {
        if (this.$refs.CLForm) {
          this.$refs.CLForm.clearValidate();
        }
      });
    },
    restData() {
      this.dialogFormVisible = false;
      this.CLForm = { ...codeLibraryForm };
    },

    append() {
      this.$refs.CLForm.validate((valid) => {
        if (valid) {
          if (!this.CLForm.gmtCreate) {
            this.CLForm.userId = this.userId
            codeLibraryList.appendCode(this.CLForm).then((res) => {
              this.$message({
                type: "success",
                message: "添加数据成功!",
              });
              this.restData();
          this.initTableList();
            });
          } else {
            codeLibraryList.update(this.CLForm).then((res) => {
              this.$message({
                type: "success",
                message: "更新数据成功!",
              });
              this.restData();
          this.initTableList();
            });
          }
          
        }
      });
    },
    removeById(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          codeLibraryList.removeById(id).then((res) => {
            this.$message({
              type: "success",
              message: "删除数据成功!",
            });
            this.restData();
            this.initTableList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    update(row) {
      //等弹窗里的form表单的dom渲染完在执行this.$refs.CLForm.clearValidate()，去除验证
      this.$nextTick(() => {
        if (this.$refs.CLForm) {
          this.$refs.CLForm.clearValidate();
        }
      });
      this.dialogFormVisible = true;
      this.CLForm = { ...row };
    },
    searchData() {
      this.initTableList();
    },
  },
};
</script>

